<template>
  <el-card class="box-card" v-loading="loading">
  <div slot="header" class="clearfix">
    <shopee-row class="row" v-model="searchForm">

      <shopee-col :span="1" vertical-align="center" align="center">
        项目
      </shopee-col>
      <shopee-col :span="4" vertical-align="center" align="center">
        <el-select v-model="projectId" placeholder="请选择" @change="changeProjectId()">
          <el-option
            v-for="item in projectList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </shopee-col>

      <shopee-col :span="1" align="center">
        配置名
      </shopee-col>
      <shopee-col :span="4">
        <shopee-input v-model="searchForm.task_name" @keyup.enter.native="search('searchForm')"></shopee-input>
      </shopee-col>
      <shopee-col :span="1">
        <el-button type="primary" @click="search('searchForm')" outline>查询</el-button>
      </shopee-col>
<!--      <shopee-col :span="1">-->
<!--        <el-button type="primary" @click="goToCreatePage" outline>新建任务</el-button>-->
<!--      </shopee-col>-->
      <br>
    </shopee-row>

    <shopee-table class=tasklistData stripe :data="tasklistData">
       <shopee-table-column prop="name" label="配置名" :width="150" fixed="left">
      </shopee-table-column>

      <shopee-table-column label="调度配置" :width="200">
        <template slot-scope="props">
          {{props.row.task_crontab}}
        </template>
      </shopee-table-column>

      <shopee-table-column prop="status" label="调度状态" :width="150">
        <template slot-scope="props">
          <div v-if="props.row.status === 'online'" class="status unread">
            <shopee-tag status="success">online</shopee-tag>
          </div>
          <div v-if="props.row.status === 'offline'">
            <shopee-tag status="invalid">offline</shopee-tag>
          </div>
        </template>
      </shopee-table-column>

      <shopee-table-column prop="owner" label="owner" :width="200">
      </shopee-table-column>

<!--      <shopee-table-column prop="project_name" label="所属项目"  :width="100">-->
<!--      </shopee-table-column>-->

       <shopee-table-column prop="webhook" label="seatalk通知群" :width="200">
      </shopee-table-column>

        <shopee-table-column prop="version_pattern" label="版本正则" :width="120">
      </shopee-table-column>

        <shopee-table-column prop="is_uat" label="uat" :width="50">
      </shopee-table-column>


       <shopee-table-column label="操作" fixed="right" :width="450">
        <template slot-scope="props">
            <el-button  size="small" @click="executeTask(props.row.id)" type="success" outline>执行</el-button>
            <el-button  v-if="props.row.status === 'online'" size="small" @click="offlineTask(props.row.id)"  type="danger" outline>下线</el-button>
            <el-button  v-if="props.row.status === 'offline'" size="small" @click="onlineTask(props.row.id)" type="danger" outline>上线</el-button>
            <el-button  size="small" @click="viewDetails(props.row.id,props.row.name,props.row.step_config)" type="primary" outline>流程配置</el-button>
            <el-button  size="small" @click="viewGlobal(props.row.id,props.row.project_id,props.row.name)" type="primary" outline>项目配置</el-button>
          <el-button  size="small" @click="toExecutePage(props.row.id,props.row.name)"  outline>日志</el-button>
        </template>
      </shopee-table-column>
    </shopee-table>
      <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[5,10, 15, 20, 25]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalRow">
      </el-pagination>


    <el-dialog :title="'项目配置-'+rowName" :visible.sync="globalDialogVisible" width="60%">

       <el-row>
             <el-col :span="24">
                <el-button @click="showHelpGit">Git配置说明</el-button>
           </el-col>

         <el-col :span="24">
           <el-tabs value="global_tab0">
             <template v-for="(item,index) in globalConfig">
              <el-tab-pane :label="item.name" :name="'global_tab'+index"><json-editor :name="'global_editor'+index" v-model=item.value></json-editor></el-tab-pane>
            </template>
           </el-tabs>
         </el-col>
       </el-row>
       <el-row>
         <el-col :span="12" style="text-align: center">
           <el-button type="primary" @click="changeGlobalConfig" >修改</el-button>
         </el-col>
           <el-col :span="12" style="text-align: center">
           <el-button @click="globalCancel" >取消</el-button>
         </el-col>
       </el-row>

    </el-dialog>

    <el-dialog :title="'流程配置-'+rowName" :visible.sync="dialogVisible" width="60%">

       <el-row>
           <el-col :span="24">
                <el-button @click="showHelp">配置说明</el-button>
           </el-col>
         <el-col :span="24">
           <el-tabs value="tab0">
             <template v-for="(item,index) in stepConfig">
              <el-tab-pane :label="item.name" :name="'tab'+index"><json-editor :name="'editor'+index" v-model="item.steps"></json-editor></el-tab-pane>
            </template>
           </el-tabs>
         </el-col>
       </el-row>
       <el-row>
         <el-col :span="12" style="text-align: center">
           <el-button type="primary" @click="changeConfig" >修改</el-button>
         </el-col>
           <el-col :span="12" style="text-align: center">
           <el-button @click="cancel" >取消</el-button>
         </el-col>
       </el-row>

    </el-dialog>

    <el-dialog :title="'执行参数'+rowName"  :visible.sync="executeDialogVisible" width="50%" v-if="executeDialogVisible">
      <execute-dialog  v-on:closeExecuteDialog="closeExecuteDialog" :task_id="executeTaskId"></execute-dialog>
    </el-dialog>

    <el-dialog title=""  :visible.sync="helpDialogVisible" width="55%" v-if="helpDialogVisible">
      <div id="markedHelp" v-html="helpContent"></div>
    </el-dialog>

  </div>
  </el-card>
  </template>

  <script>
    import {api, getRequest, postRequest} from "@/api/commit";
    import JsonEditor from '@/components/JsonEditor'
    import ExecuteDialog from '@/components/schedulex/ExecuteDialog'
    import marked  from 'marked'
    import {marked2Html} from "@/api/schedulex";
    export default {
      name : "TaskListTable",
      components: {
        JsonEditor,
        ExecuteDialog
      },
      data() {
        return {
          projectId:2,
          projectList: [{
              id: 3,
              name: 'CRM'
            }],
          tasklistData: [],
          currentPage: 1,
          totalRow: 0,
          pageSize: 10 ,
          dialogVisible: false,
          globalDialogVisible: false,
          rowName: "",
          helpDialogVisible:false,
          helpContent:"",
          dialogData:"",
          executeDialogVisible:false,
          executeTaskId:0,
          executeParams:{},
          executeTaskData:{},
          offlineTaskData:{},
          onlineTaskData:{},
          selectedValue: '',
          value: '',
          searchForm:{
            task_name:'',
          },
          changeForm:{
            id:'',
            step_config:'',
          },
          globalForm:{
            project_id:'',
            task_id:'',
            config:'',
          },
          globalConfig:[
            {
              "name":"Git配置",
              "value":[],
              "type":"json"
            }
          ],
          loading: false,
          stepConfig:[
            {
              "name":"发布准备阶段",
              "steps":[]
            }
          ]
        }
      },

      methods: {

        viewDetails(id,rowName,data) {
          this.changeForm.id=id
          // this.dialogData=data
          this.rowName=rowName
          this.dialogVisible= true
          this.stepConfig=data
        },
        changeConfig(){
          // console.info(this.stepConfig)
          postRequest(api['update_step_config'],{"id":this.changeForm.id,"step_config":this.stepConfig}).then((res) => {
            res = res.resultReturn
            this.init_data();
          }, (error) => {
            console.info(error)
          })
        },
        cancel(){
          this.dialogVisible=false
        },
        viewGlobal(task_id,project_id,rowName) {
          this.globalForm.project_id=project_id
          this.globalForm.task_id=task_id
          getRequest(api['get_global'],{"task_id":task_id,"project_id":project_id}).then((res) => {
            res = res.resultReturn
            this.globalConfig=res.data
            this.rowName=rowName
            this.globalDialogVisible= true
          }, (error) => {
            console.info(error)
          })
        },
        changeGlobalConfig(){
          // console.info(this.globalConfig)
          postRequest(api['update_global'],{"task_id":this.globalForm.task_id,"project_id":this.globalForm.project_id,"data":this.globalConfig}).then((res) => {
            res = res.resultReturn
            this.globalDialogVisible= false
          }, (error) => {
            console.info(error)
          })
        },
        globalCancel(){
          this.globalDialogVisible=false
        },

        showHelp(){
          getRequest(api['step_get_marked_content'],{key:"step_config"}).then((res) => {
            this.helpContent=marked2Html(res.resultReturn.data)
            this.helpDialogVisible=true
          }, (error) => {
            console.info(error)
          })

        },
        showHelpGit(){
          getRequest(api['step_get_marked_content'],{key:"git_config"}).then((res) => {
            this.helpContent=marked2Html(res.resultReturn.data)
            this.helpDialogVisible=true
          }, (error) => {
            console.info(error)
          })

        },
        handleSizeChange(val) {
             this.pageSize = val;
             this.init_data();
          },
          //当前页变换
          handleCurrentChange(val) {
                 this.currentPage = val;
                 this.init_data();
          },
        changeProjectId(){
          if (this.projectId!==0){
            this.$cookies.set('projectId',this.projectId)
            this.init_data()
          }

        },
        init_select(){
          // console.log("init_select")
          getRequest(api['project_list'],{}).then((res) => {
            res = res.resultReturn
            this.projectList= res.data
            var projectId=this.$cookies.get('projectId')
            // // console.log(projectId)
            if(projectId!==null && projectId!==0 ){
               this.projectId=parseInt(projectId)
            }
             this.init_data()
          }, (error) => {
            console.info(error)
          })
        },
        init_data() {
          getRequest(api['task_list'],{
            "project_id":this.projectId,
            "task_name":this.searchForm.task_name,
            "page_size":this.pageSize,"page":this.currentPage}).then((res) => {
            res = res.resultReturn
            this.tasklistData= res.data
            this.totalRow=res.total
            this.dialogVisible=false
          }, (error) => {
            console.info(error)
          })
        },

        executeTask(id,rowName) {
          this.executeTaskId=id
          this.rowName=rowName
          this.executeDialogVisible= true
          // let params = {
          //   "id":id
          // }
          // postRequest(api['task_execute'],params).then((res) => {
          //   res = res.resultReturn
          //   this.executeTaskData= res.data
          // }, (error) => {
          //   console.info(error)
          // })
        },
        closeExecuteDialog() {
          console.info("2")
          this.executeDialogVisible= false
        },
        offlineTask(id) {
          let params = {
            "id":id
          }
          this.loading=true
          postRequest(api['task_offline'],params).then((res) => {
            res = res.resultReturn
            this.offlineTaskData= res.data
            this.init_data()
            this.loading=false
          }, (error) => {
            this.loading=false
            console.info(error)
          })
        },

        onlineTask(id) {
          let params = {
            "id":id
          }
          postRequest(api['task_online'],params).then((res) => {
            res = res.resultReturn
            this.onlineTaskData= res.data
            this.init_data()
          }, (error) => {
            console.info(error)
          })
        },
        search(searchForm) {
          let params = Object.assign({}, this.searchForm);
          getRequest(api['task_list'], params).then((res)=>{
            res = res.resultReturn
            this.tasklistData= res.data
            this.totalRow=res.total
          },(error)=>{
            this.resultReturn = "请检查您的输入是不是有问题&依赖方报错俺也没办法"
          })
        },
        toExecutePage: function(id){
          this.$router.push({
            path: '/ExecuteListView',
            query:{
              id:id
            }
          })
        },
        goToCreatePage(){
          this.$router.push('/CreateTaskView');
        }
      },
      mounted () {
        this.init_select()

      }
    }
  </script>
